package com.pay.service.impl;

import com.group.common.utils.HttpUtils;
import com.group.common.utils.R;
import com.pay.service.DetectionService;
import com.pay.util.OSSFileUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author lins
 * @date 2021/11/25 19:29
 */
@Service
@Slf4j
public class DetectionServiceImpl implements DetectionService {
    @Override
    public R detection(MultipartFile file) {
        //上传文件到oss
        String videoUrl = null;
        try {
            videoUrl = OSSFileUtil.uploadFile(file);
        } catch (IOException e) {
            e.printStackTrace();
        }
        HttpResponse response = detectionMethod(videoUrl);
        if (response.getStatusLine().getStatusCode()==200){
            return R.ok("活体检测通过");
        }
        return R.error("活体检测失败");
    }

    public HttpResponse detectionMethod(String videoUrl){
        String host = "https://jmmum.market.alicloudapi.com";
        String path = "/lifecheck";
        String method = "POST";
        String appcode = "6337e786cbb74df3b5972e7a32bcd906";
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        //根据API的要求，定义相对应的Content-Type
        headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        Map<String, String> querys = new HashMap<String, String>();
        Map<String, String> bodys = new HashMap<String, String>();
        bodys.put("complexity", "0");
        bodys.put("motion", "BLINK");
        bodys.put("videoUrl", videoUrl);
        HttpResponse response = null;

        try {
            /**
             * 重要提示如下:
             * HttpUtils请从
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java
             * 下载
             *
             * 相应的依赖请参照
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml
             */
            response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
            System.out.println(response.toString());
            System.out.println(EntityUtils.toString(response.getEntity()));
            return response;
            //获取response的body
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
